package com.hongxing.baseaar.base

import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VB : ViewBinding> : Fragment() {
    protected var mRootView: View? = null
    protected lateinit var binding: VB


    fun isBindingInit(): Boolean {
        return ::binding.isInitialized
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        var superClass = javaClass.genericSuperclass
        if (superClass !is ParameterizedType) {
            superClass = javaClass.superclass.genericSuperclass
        }
        val clazz = (superClass as ParameterizedType).actualTypeArguments[0] as Class<VB>
        val method = clazz.getMethod(
            "inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java
        )
       /* if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }*/
        binding = method.invoke(null, inflater, container, false) as VB
        mRootView = binding.root
        return this.mRootView
    }

    override fun onResume() {
        super.onResume()
        initView()
    }

   /* @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onMessageEvent(event: MessageEvent) {

    }*/

    fun bindingIsInit(): Boolean {
        return ::binding.isInitialized
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

   /* fun showToast(msg: String?) {
        requireActivity().runOnUiThread {
            Toaster.show(msg.toString())
        }
    }*/

    open fun Logmsg(msg: String?) {
        //  AppLog.LogeWriteLogFile(msg.toString())
        Log.e("test", msg.toString())
    }



    /**
     * 按键按下事件回调
     */
    fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // 默认不拦截按键事件
        return false
    }

    /**
     * 按键抬起事件回调
     */
    fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        // 默认不拦截按键事件
        return false
    }

    open fun LogMsg(msg: String?) {
        //AppLog.LogeWriteLogFile(msg.toString())
        Log.e("test", msg.toString())
    }

    override fun onDestroy() {
       /* if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }*/
        super.onDestroy()
    }


    abstract fun initView()
}